package edu.mtu.citizenscience.ethnography;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import edu.mtu.citizenscience.ethnography.database.Interview;
import edu.mtu.citizenscience.ethnography.util.DataServiceActivity;
import edu.mtu.citizenscience.ethnography.util.Util;

import android.os.Bundle;
import android.widget.DatePicker;
import android.widget.EditText;

/**
 * Allows the user to input data for the interview.  Currently lacks
 * a field for the name of the interviewer, due to the size of the
 * DatePicker widget.  
 * due to using buttons to trigger database reads and writes. There 
 * might be a way around it using intent extras, but I haven't looked
 * into it yet.
 * @author john
 *
 */
public class InputInterviewDataActivity extends DataServiceActivity {

	// Global activity variables
	private Interview currentInterview = null;
	private Integer currentInterviewID = null;
	
	// Text fields
	private EditText storyTitleField;
	private EditText subjectNameField;
	private EditText interviewLocationField;
	private DatePicker dateField;
	private EditText interviewerField;
	private EditText notesField;
	
	//Boilerplate log tag
	@SuppressWarnings("unused")
	private static final String LOG_TAG = "InputInterviewDataActivity";
	
	/**
	 * Loads the layout on activity creation.  Nothing special here
	 * 
	 */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_input_interview_data);
        
        if (savedInstanceState == null) {
        	Bundle extras = getIntent().getExtras();
        	//if there is a interview id in extras, grab it
        	if ( extras != null )
        		currentInterviewID = extras.getInt(Util.ID_KEY);
        } else {
        	currentInterviewID = savedInstanceState.getInt(Util.ID_KEY);
        }

        storyTitleField = (EditText) findViewById(R.id.editStoryTitle);
        subjectNameField = (EditText) findViewById(R.id.editSubjectName);
        interviewLocationField = (EditText) findViewById(R.id.editInterviewLocation);
        dateField = (DatePicker) findViewById(R.id.editInterviewDate);
        interviewerField = (EditText) findViewById(R.id.editInterviewInterviewer);
        notesField = (EditText) findViewById(R.id.editInterviewDetails);
    }
    
    
	/**
	 * onStart, pulls the current interview ID from the intent extras.
	 * Cannot create a new interview here, as the database connection
	 * isn't resolved until the function finishes.
	 */
    @Override
	protected void onStart(){
    	
        subjectNameField.setEnabled(false);
        interviewLocationField.setEnabled(false);
        dateField.setEnabled(false);
        interviewerField.setEnabled(false);
        notesField.setEnabled(false);
        
        super.onStart();
    }
    
    @Override
    protected void performDatabaseOperation() {
    	if (isBound()) {
    		currentInterview = getService().getInterview(currentInterviewID);
    		
    		storyTitleField.setText(currentInterview.getStoryTitle());
    		subjectNameField.setText(currentInterview.getSubjectName().getFullName());
    		interviewLocationField.setText(currentInterview.getLocationName());
    		Calendar calendar = new GregorianCalendar();
    		calendar.setTime(currentInterview.getDate());
    		dateField.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), null);
    		interviewerField.setText(currentInterview.getInterviewerName().getFullName());
    		notesField.setText(currentInterview.getNotes());
    		
    		subjectNameField.setEnabled(true);
    		interviewLocationField.setEnabled(true);
    		dateField.setEnabled(true);
    		interviewerField.setEnabled(true);
    		notesField.setEnabled(true);
    	}
    }
    
    @Override
    protected void onStop() {
    	//put the interview information into the database
    	commitInterviewData();
    	super.onStop();
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
    	outState.putInt(Util.ID_KEY, currentInterviewID);
    	super.onSaveInstanceState(outState);
    }
    
    
    /**
     * Helper method to clean up the database commit code.
     * Individually pulls the data from each of the text fields/DatePicker and commits
     * it to the database.
     */
    private void commitInterviewData() {
    	String text;
    	
    	text = storyTitleField.getText().toString();
    	
    	currentInterview.setStoryTitle(text);
    	//first to be committed is the subject's name 
    	
    	//pull the string from the widget
    	text=subjectNameField.getText().toString();
    	
    	//commit the string into the database
    	currentInterview.setSubjectName(parseRawName(text));
    	
    	//Next is the Location
    	text=interviewLocationField.getText().toString();
    	
    	currentInterview.setLocationName(text);
    	
    	//Followed by the date
    	currentInterview.setDate(new Date(dateField.getYear() - 1900,
    			dateField.getMonth(),
    			dateField.getDayOfMonth()));
    	
    	//The interviewer name
    	text = interviewerField.getText().toString();
    	
    	currentInterview.setInterviewerName(parseRawName(text));
    	
    	//And the interview details
    	text=notesField.getText().toString();
    	
    	currentInterview.setNotes(text);
    	
    	// Save it to the database
    	getService().saveInterviewWithoutRename(currentInterview);
    }
    
    private static Interview.Name parseRawName(String rawName) {
    	Interview.Name name = new Interview.Name();
    	int index = rawName.indexOf(',');
    	if (index != -1) {
    		// Process name under the assumption of LAST_NAME, FIRST_NAME
    		String rawLastName = rawName.substring(0, index);
    		String rawFirstName = rawName.substring(index + 1);
    		name.setFirstName(rawFirstName.trim());
    		name.setLastName(rawLastName.trim());
    	} else {
    		index = rawName.indexOf(' ');
    		if (index != -1) {
    			String rawFirstName = rawName.substring(0, index);
    			String rawLastName = rawName.substring(index);
    			name.setFirstName(rawFirstName.trim());
    			name.setLastName(rawLastName.trim());
    		} else {
    			name.setLastName(rawName.trim());
    		}
    	}
    	
    	return name;
    }
    
}
